package com.bobo.controller.user;

import com.bobo.constant.StatusConstant;
import com.bobo.entity.Vegetable;
import com.bobo.result.Result;
import com.bobo.service.VegetableService;
import com.bobo.vo.VegetableVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class VegetableController {
    @Autowired
    private VegetableService vegetableService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<VegetableVO>> list(Long categoryId) {
        //构造redis的key dish_分类id
        String key = "dish_"+ categoryId;

        //查询redis中有无菜品数据
        List<VegetableVO> list =(List<VegetableVO>) redisTemplate.opsForValue().get(key);
        if (list != null&&list.size()>0) {
            //有就返回，无需查询数据库
            return Result.success(list);
        }
        //不存在，查数据库


        Vegetable vegetable = new Vegetable();
        vegetable.setCategoryId(categoryId);
        vegetable.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
        list = vegetableService.listWithFlavor(vegetable);
        //，缓存到redis中
        redisTemplate.opsForValue().set(key,list);
        return Result.success(list);
    }

}
